<template>
  <div class="action-app-form">
    <div class="action-app-form-item">
      <div class="title">{{ $t('common.connector.selectApplication') }}</div>
      <search-tree
        :current-node-key="app.data.appId"
        :tree-data="moduleList"
        :default-props="appTreeDefaultProps"
        :is-trigger="true"
        @select="handleTreeSelect"
      >
      </search-tree>
    </div>
    <div class="action-app-form-item">
      <div class="title">{{ $t('common.connector.executeAction') }}</div>
      <search-tree
        :current-node-key="app.data.bizTypeAndId"
        :tree-data="apiList"
        :default-props="treeDefaultProps"
        :is-trigger="true"
        @select="handleActionTreeSelect"
        :defaultSearchText="toBizTypeName"
        @changeParent="changeParent"
      >
      </search-tree>

      <div class="action-app-form-item__action-way" v-if="isSupportCodeWrite && toBizTypeId && loading">
        <div class="title">动作方式</div>
        <el-radio-group v-model="executeAction.mappingType">
          <el-radio-button v-for="item in actionWay" :key="item.value" :label="item.value">{{ item.name }}</el-radio-button>
        </el-radio-group>
      </div>
      <div v-loading="toBizTypeId && !loading">
        <div class="action-app-form-item__select" v-show="executeAction.mappingType === 'fieldRelation'">
          <template v-if="['INSERT', 'SELECT'].includes(executeAction.action)">
            <div class="action-app-form-item">
              <div class="title">{{ $t('common.base.createRuler') }}</div>
              <div class="desc">{{ $t('common.connector.trigger.validate.text10') }}</div>
              <ConnectorModuleConnectorDialogDetailActionCreate
                v-if="loading"
                :value="executeAction.insertFieldOptions"
                :to-field-list="toFieldList"
                :from-field-list="fromFieldList"
                :from-biz-type-name="fromBizTypeName"
                :to-biz-type-name="toBizTypeName"
                :to-biz-type-id="toBizTypeId"
                :show-detail-type="false"
                @input="onConnectorInsertRuleFormInputHandler"
                :show-title="false"
                :required-show-del="false"
                validation
                show-text
                :is-wiki="isWiki"
              />
            </div>
          </template>
          <template v-if="executeAction.action == 'UPDATE'">
            <div v-if="selectFieldList && selectFieldList.length" class="action-app-form-item">
              <div class="title">{{ $t('common.connector.trigger.validate.text11') }}</div>
              <div class="desc">{{ $t('common.connector.trigger.validate.text12') }}</div>
              <ConnectorModuleConnectorDialogDetailActionQuery
                v-if="loading"
                :to-field-list="selectFieldList"
                :from-field-list="fromFieldList"
                :to-biz-type-name="toBizTypeName"
                :to-biz-type-id="toBizTypeId"
                :from-biz-type-name="fromBizTypeName"
                :value="executeAction.updateFieldOptions.select"
                @input="onUpdateFormInputSelectHandler"
                :show-title="true"
              />
            </div>
            <div class="action-app-form-item">
              <div class="title">{{ selectFieldList && selectFieldList.length ? $t('common.connector.trigger.validate.text13') : '选择需要修改的字段' }}</div>
              <div class="desc">{{ $t('common.connector.trigger.validate.text14') }}</div>
              <ConnectorModuleConnectorDialogDetailActionCreate
                v-if="loading"
                :value="executeAction.updateFieldOptions.update"
                :to-field-list="toFieldList"
                :from-field-list="fromFieldList"
                :from-biz-type-name="fromBizTypeName"
                :to-biz-type-name="toBizTypeName"
                :to-biz-type-id="toBizTypeId"
                :show-detail-type="false"
                @input="onUpdateFormInputInsertHandler"
                :show-title="false"
                show-text
                is-update
                validation
              />
            </div>
          </template>
        </div>
        <template v-if="executeAction.action == 'DELETE'">
          <div class="action-app-form-item" v-if="executeAction.mappingType === 'fieldRelation'">
            <div class="title">{{ $t('common.connector.trigger.validate.text15') }}</div>
            <div class="desc">{{ $t('common.connector.trigger.validate.text16') }}</div>
            <ConnectorModuleConnectorDialogDetailActionQuery
              v-if="loading"
              :to-field-list="toFieldList"
              :from-field-list="fromFieldList"
              :to-biz-type-name="toBizTypeName"
              :from-biz-type-name="fromBizTypeName"
              :value="executeAction.deleteFieldOptions.delete"
              @input="onConnectorDeleteRuleFormHandler"
              :show-title="true"
            />
          </div>
          <div class="content-code" v-else>
            <el-button type="text" @click="openCodeHelp">编码规范及使用帮助</el-button>
            <action-codemirror :value.sync="executeAction.javaCode"></action-codemirror>
          </div>
          <div class="action-app-form-item">
            <div class="title">{{ $t('common.connector.trigger.deleteNotification.title') }}</div>
            <el-form ref="form" :model="executeAction.deleteFieldOptions.message" label-width="80px">
              <el-form-item :label="$t('common.connector.trigger.deleteNotification.receiver')" required>
                <el-select
                  v-model="executeAction.deleteFieldOptions.message.paasReceiver"
                  :placeholder="$t('common.connector.trigger.deleteNotification.selectReceiver')"
                  value-key="name"
                  multiple>
                  <el-option
                    v-for="item in paasReceiverList"
                    :label="item.name"
                    :value="item"
                    :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('common.connector.trigger.msgTemplate.name')" required>
                <div class="template-content" style="min-height:280px!important;">
                  <div class="system-message-template">
                    <h3>{{ $t('common.connector.trigger.msgTemplate.title') }}</h3>
                    <div class="desc">{{ $t('common.connector.trigger.msgTemplate.desc') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item1') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item2') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item3') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item4') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item5') }}</div>
                    <div class="template-content-item">{{ $t('common.connector.trigger.msgTemplate.item6') }}</div>
                    <div class="date">2023-01-01 12:12:13</div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <div class="content-code" v-if="executeAction.mappingType === 'code' && executeAction.action != 'DELETE'">
          <el-button type="text" @click="openCodeHelp">编码规范及使用帮助</el-button>
          <action-codemirror :value.sync="executeAction.javaCode"></action-codemirror>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
import SearchTree from '@src/component/form/components/FormConnector/SearchTree/SearchTree.vue';
import {
  ConnectorModuleConnectorDialogDetailActionQuery,
  ConnectorModuleConnectorDialogDetailActionCreate,
} from '@src/modules/connector/components'
import actionCodemirror from '@src/modules/connector/view/setting/components/workflow/components/drawers/actionCodemirror.vue'

import _ from 'lodash'
import * as triggerApi from '@src/modules/connector/api/trigger';
import * as MessageApi from '@src/api/Message';
/* util */
import {
  createConnectorRuleFormItem,
} from '@src/modules/connector/util'
import { addSupportProperty, convertJsonFieldTypeToFieldList, transformServeVlaue, getToStartNodeFromApiId } from '@src/modules/connector/view/setting/components/workflow/utils/index.js';
import { t } from '@src/locales';
import { isOpenGrayByGrayFunctionName } from '@src/util/grayInfo'
import { GrayFunctionEnum } from '@model/grayFunction'
import { ConnectorOptionsActionEnum } from 'src/modules/connector/model/enum'
import { convertData } from '@src/modules/connector/util/sampleCode.ts'

export default {
  name:'ActionAppDrawer',
  provide: {
    isTrigger: true,
  },
  props:{
    nodeConfig:{
      type:Object,
      default:()=>({})
    },
    moduleList:{
      type:Array,
      default:()=>([])
    },
    parent:{
      type:Object,
      default:()=>({})
    }
  },
  computed:{
    parentApp() {
      return this.parent.getParent().isTrigger
        ? this.parent.getParent().getParent().data
        : this.parent.getParent().data;
    },
    fromBizTypeName(){
      return t('trigger.beforeForm')
    },
    toBizTypeName(){
      return this.app?.data.name || ''
    },
    toBizTypeId(){
      return this.app?.data?.bizTypeId || ''
    },
    toBizType(){
      return this.appBizType || ''
    },
    isWiki() {
      return this.appBizType === 'WIKI' && this.executeAction.action === 'INSERT'
    },
    defaultToNodeData() {
      return this.app?.data?.defaultToNodeData || {}
    },
    actionWay() {
      return [{
        name: '配置方式',
        value: 'fieldRelation'
      }, {
        name: t('trigger.codeMethods'),
        value: 'code'
      }]
    },
    isSupportCodeWrite() {
      return isOpenGrayByGrayFunctionName(GrayFunctionEnum.TRIGGERCODE) && this.showIsSupportCodeWrite
    }
  },
  watch:{
    nodeConfig:{
      handler(newVal){
        this.app = newVal
        if(!this.app.isEdit){
          this.initActionApp()
        }
      },
      deep:true,
      immediate:true
    },
    'app.data.appId': {
      handler(newVal, oldVal) {
        // 选择应用更改后，重新获取api列表
        if(!newVal) {
          this.initActionApp(true)
        } else {
          if(newVal && newVal != oldVal) {
            // const app = this.moduleList.find(item => item.appId == newVal)
            const app = this.getAppByAppId(newVal)
            if(!app) return
            this.appBizType = app.bizType
            this.getOptions(app)
            if(oldVal) {
              this.app.data.bizType = ''
              this.app.data.bizTypeId = ''
              this.app.data.bizTypeAndId = ''
              this.$emit('update:nodeConfig', this.app)
            }
          }
        }
      },
      deep:true,
      immediate:true
    },
    'app.data.bizTypeId':{
      handler(newVal, oldVal){
        // 执行应用的api变化后，获取表单字段
        if(newVal === oldVal) return
        if(newVal) {
          this.getApiFiledInfo(newVal)
        } else {
          this.initActionApp(true)
        }
      },
      deep:true,
      immediate:true
    },
    parentApp:{
      handler(newVal) {
        // console.log('drawer actionApp parentApp', newVal)
        if(this.app.isEdit){
          this.app.isEdit = false
        }
        this.$emit('update:nodeConfig', this.app)
      },
      deep: true,
      immediate: true
    }
  },
  data(){
    return{
      loading: false,
      app:this.nodeConfig,
      appTreeDefaultProps:{
        children: 'children',
        label: 'name',
        key: 'appId',
      },
      treeDefaultProps:{
        children: 'children',
        label: 'name',
        key: 'bizTypeAndId',
      },
      apiList: [],
      actionList:[],
      toFieldList:[],
      fromFieldList:[],
      executeAction:{
        javaCode: convertData,
        action:'',
        apiId: '',
        mappingType: 'fieldRelation',
        executeMethod:2,
        insertFieldOptions:[],
        deleteFieldOptions:{
          delete:[],
          message:{
            paasReceiver:[]
          }
        },
        updateFieldOptions:{
          select:[],
          update:[]
        },
      },
      paasReceiverList:[
        {id:1, type:4, name:this.$t('common.auth.roleNameList[0]')},
        // {id:'createUser', type:6, name:this.$t('common.base.createUser')}
      ],
      triggerTemplateFields: [],
      selectFieldList: null,
      appBizType: '', // 选择应用的类型
      firstLoad: true,
      showIsSupportCodeWrite: true, // 根据应用类型去判断是否显示写代码
      parentNode: null
    }
  },
  methods:{
    handleActionWayChange() {
      // this.executeAction.javaCode = ''
    },
    checkIsShowSupportWriteCode(inside, action) {
      (inside && action === ConnectorOptionsActionEnum.Insert) || !inside
        ? this.showIsSupportCodeWrite = true
        : this.showIsSupportCodeWrite = false

    },
    getAppByAppId(targetAppId) {
      for (let i = 0; i < this.moduleList.length; i++) {
        const item = this.moduleList[i];
        if (item.children?.length) {
          const appItem = item.children.find(i =>i.appId == targetAppId)
          if(appItem) return appItem;
        }
      }
      return null;
    },
    async handleTreeSelect(val){
      // 选择api接口后
      this.executeAction.updateFieldOptions = {
        select:[],
        update:[]
      }
      this.executeAction.insertFieldOptions = []
      this.executeAction.mappingType = 'fieldRelation'
      this.executeAction.deleteFieldOptions = {
        delete:[],
        message:{
          // paasReceiver:_.cloneDeep(this.paasReceiverList)
        }
      }
      let data = {
        appId: '',
        name: '',
        logo: '',
        bizType: '',
        bizTypeId: '',
        bizTypeAndId: '',
      }
      if(val){
        let {appId, name, logo, bizType, bizTypeId, bizTypeAndId, inside } = val
        data = {appId, name, logo, bizType, bizTypeId, bizTypeAndId}
        this.checkIsShowSupportWriteCode(inside, val.action)
      }

      data.executeAction = this.executeAction
      data.executeAction.action = val.action
      data.executeAction.actionWay = ''
      if (this.parentNode?.action == "PAAS_WORKFLOW") {
        data.executeAction.paasNodeId = this.parentNode?.id;
      }
      this.app.data = data
      this.firstLoad = false
      this.app.childNodes = []

      this.$emit('update:nodeConfig', this.app)
    },
    async handleActionTreeSelect(val){
      await this.getApiFiledInfo(val.bizTypeId)
      this.handleTreeSelect(val)
    },
    getParentNode(nodeId, nodes = []) {
      for (const node of nodes) {
        if (node.children && node.children.some(child => child.id === nodeId)) {
          return node;
        } else if (node.children) {
          const parentNode = this.getParentNode(nodeId, node.children);
          if (parentNode) {
            return parentNode;
          }
        }
      }
      return null;
    },
    // 根据fromApiId和toApiId获取表单字段
    getApiFiledInfo: _.debounce(async function(toApiId) {
      // loading写在这里不要改,因为选择api后就需要将组件销毁然后接口请求后再显示
      this.loading = false
      await this.getPaasReceiverList();
      const fromApiIds = getToStartNodeFromApiId(this.nodeConfig)
      const p = {
        fromApiIds: fromApiIds.slice(1, fromApiIds.length),
        toApiId
      }
      // 如果执行应用是知识库 需要获取表单字段
      if(this.isWiki) {
        try {
          const p = { bizType: this.parentApp.appBizType, bizTypeId: this.parentApp.bizTypeId }
          await this.getTriggerTemplateField(p)
        } catch (e) {
          console.warn(e)
        }
      }
      this.selectFieldList = []
      this.fromFieldList = []
      this.toFieldList = []
      triggerApi.getApiFiledInfo(p).then(res=>{
        this.loading = true
        if(res.status != 0) {
          this.$message.warning(res.message || '')
          return
        }

        const result = res?.data || {}

        // 拆分json类型字段（子表单）
        result.toFieldList = convertJsonFieldTypeToFieldList(result.toFieldList)
        result.selectFieldList = convertJsonFieldTypeToFieldList(result.selectFieldList)

        this.selectFieldList = addSupportProperty(result.selectFieldList || [], 'supportSelect')

        this.actionList = res.data?.actionList || []
        this.toFieldList = addSupportProperty(result?.toFieldList || [], 'supportSelect', 'supportInsert', 'supportUpdate')
        this.fromFieldList = addSupportProperty(result?.fromFields || [], 'supportSelect', 'supportInsert')



        this.firstLoad && this.initOptionsListValue()

        this.toFieldList = this.toFieldList.map(item => {
          // 如果是知识库的富文本字段，将from表单和对应字段传过去
          if(this.isWiki && item.fieldType === 'rich_text') {
            item.setting.fromBizTypeName = this.fromBizTypeName
            item.setting.templateFields = this.triggerTemplateFields
          }
          return item
        })

        if((!this.executeAction?.insertFieldOptions || !this.executeAction?.insertFieldOptions.length) && !this.app.isEdit){
          if(this.executeAction.action !== 'INSERT') {
            this.executeAction.insertFieldOptions = []
          } else {
            this.executeAction.insertFieldOptions = this.toFieldList.map(toField => {
              let formItem = createConnectorRuleFormItem(toField)
              // 知识库取值方式只有固定值
              if(this.isWiki) formItem.condition = 'fixedValue'
              return formItem
            })
            this.$nextTick(() => {
              this.userNameStyleOverlapPolyfill()
            })
          }
        }

      })
    }, 100),

    /**
     * Description 初始化相关的设置的field的映射关系的value
     * @returns {any}
     */
    initOptionsListValue() {
      // 这里的代码其实是utils中转换copy到这里
      const insertFieldOptions = this.app.data.executeAction.insertFieldOptions
      this.app.data.executeAction.insertFieldOptions = insertFieldOptions.length ? insertFieldOptions : transformServeVlaue(this.defaultToNodeData?.fieldOptions?.insert, this.toFieldList, false)

      const updateFieldOptions = this.app.data.executeAction.updateFieldOptions
      this.app.data.executeAction.updateFieldOptions = {
        select: updateFieldOptions?.select?.length ? updateFieldOptions.select : transformServeVlaue(this.defaultToNodeData?.fieldOptions?.select, this.selectFieldList || [], true),
        update: updateFieldOptions?.update?.length ? updateFieldOptions.update : transformServeVlaue(this.defaultToNodeData?.fieldOptions?.update, this.toFieldList || [], false)
      }

      const deleteFieldOptions = this.app.data.executeAction.deleteFieldOptions
      this.app.data.executeAction.deleteFieldOptions = {
        ...this.app.data.executeAction.deleteFieldOptions,
        delete: deleteFieldOptions?.delete?.length ? deleteFieldOptions.delete : transformServeVlaue(this.defaultToNodeData?.fieldOptions?.delete, this.toFieldList || [], true),
      }

      this.$emit('immediatelyUpdate', this.app)
    },
    // 根据应用的appId获取执行应用的api列表
    async getOptions(app){
      const p = {
        appId: app.appId,
        direction: 'to',
      }
      triggerApi.getModuleListV2(p).then(res=>{
        // 处理数据跟以前保持一致
        if(res.status != 0) {
          this.apiList = []
          this.$message.warning(res.message || '')
          return
        }
        this.apiList = this.recursiveList(res.data, app)
      })
      this.app.isEdit = false
    },
    recursiveList(moduleList, app) {
      return moduleList.map(item => {
        item.appId = app.appId;
        item.logo = app.logo;
        item.bizTypeId = item.id;
        item.bizTypeAndId = `${item.bizType},${item.bizTypeId}`;
        if(item?.children?.length) {
          item.children = this.recursiveList(item.children, app);
        }
        return item;
      });
    },
    // 获取选择应用表单字段
    async getTriggerTemplateField(params) {
      try {
        const { status, data } = await MessageApi.getTriggerTemplateField(params)
        if(status !== 0) return
        this.triggerTemplateFields = data || []
      } catch (error) {
        console.log(error)
      }
    },
    initActionApp(isInit){
      const initExecuteAction = {
        javaCode: convertData,
        action:'',
        apiId: '',
        executeMethod:2,
        mappingType: 'fieldRelation',
        insertFieldOptions:[],
        inside: true,
        deleteFieldOptions:{
          delete:[],
          message:{
            paasReceiver:_.cloneDeep(this.paasReceiverList)
          }
        },
        updateFieldOptions:{
          select:[],
          update:[]
        }
      }
      if(isInit) {
        this.executeAction = initExecuteAction
      } else {
        this.executeAction = this.app.data?.executeAction || initExecuteAction
        this.executeAction.javaCode = this.executeAction.javaCode || convertData
      }
    },

    // 新建规则
    onConnectorInsertRuleFormInputHandler(val){
      this.executeAction.insertFieldOptions = val
    },

    // 编辑
    onUpdateFormInputSelectHandler(val){
      this.executeAction.updateFieldOptions.select = val
    },
    onUpdateFormInputInsertHandler(val){
      this.executeAction.updateFieldOptions.update = val
    },

    // 删除查询
    onConnectorDeleteRuleFormHandler(val){
      this.executeAction.deleteFieldOptions.delete = val
    },
    /**
     * @description 用户名样式重叠补丁
     */
    userNameStyleOverlapPolyfill() {

      const userInputList = this.$el.querySelectorAll('.user-search input') || []

      userInputList.forEach(userInputElement => {
        if (userInputElement.value) {
          userInputElement.value = ''
          userInputElement.placeholder = ''
        }
      })

    },
    getPaasReceiverList() {
      MessageApi.getDynamicMessageField({
        apiIdList: getToStartNodeFromApiId(this.nodeConfig),
        side: 0,
      }).then(res => {
        if(res.status === 0) {
          this.paasReceiverList = res.data.map(i => {
            return {
              id: i.enName,
              name: i.cnName,
              type: '6',
            }
          })
          this.paasReceiverList.push({id:1, type:4, name:this.$t('common.auth.roleNameList[0]')})
        }
      })
    },
    // 打开编码规范及使用帮助
    openCodeHelp(){
      window.open('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gre7yumc5sz4ewod/dklg7gkm64cya8l4/ox8c8k8i3hp1g6do.html');
    },
    changeParent(val){
      this.parentNode = val;
    }
  },
  components:{
    [SearchTree.name]:SearchTree,
    ConnectorModuleConnectorDialogDetailActionCreate,
    ConnectorModuleConnectorDialogDetailActionQuery,
    actionCodemirror
  }
}
</script>
<style lang="scss" scoped>
.template-content{
  background: #F5F5F5;
  border-radius: 4px;
  overflow-y: auto;
  padding: 20px;
  .system-message-template{
    padding: 10px 0 10px 16px;
    border-radius: 4px;
    background-color: #fff;
    width: 350px;
    h3{
      margin-bottom: 0;
    }
    .desc{
      font-size: 13px;
    }
    .template-content-item{
      font-size: 14px;
      line-height: 24px;
    }
    .date{
      margin-top: 20px;
    }
  }
}
.w-full{
  width: 100%;
}

.content-code {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  .el-button {
    margin-bottom: 10px;
  }
  .action-app-codemirror {
    width: 100%;
  }
}
</style>
